package com.pww.movie.utils;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Component
public class MinioUploadUtil {
    /**
     * 初始化桶（如果不存在则创建）
     */
    public void initBucket(MinioClient minioClient, String bucketName) throws Exception {
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 上传文件到指定桶
     * @param minioClient Minio客户端
     * @param bucketName 桶名
     * @param file 文件
     * @param objectName 对象名
     * @return 文件访问URL
     */
    public static String uploadFile(MinioClient minioClient, String bucketName, MultipartFile file, String objectName, String endpoint) throws Exception {
        InputStream inputStream = file.getInputStream();
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(inputStream, file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build()
        );
        return endpoint + "/" + bucketName + "/" + objectName;
    }

    // 批量上传本地目录下的m3u8和ts文件到MinIO，并返回m3u8文件的访问URL
    public String uploadDir(MinioClient minioClient, String bucketName, String localDir, String minioDir, String endpoint) throws Exception {
        java.io.File dir = new java.io.File(localDir);
        if (!dir.exists() || !dir.isDirectory()) {
            throw new IllegalArgumentException("本地目录不存在: " + localDir);
        }
        String m3u8Url = null;
        for (java.io.File file : dir.listFiles()) {
            if (file.isFile() && (file.getName().endsWith(".m3u8") || file.getName().endsWith(".ts"))) {
                String objectName = minioDir + file.getName();
                try (InputStream inputStream = new java.io.FileInputStream(file)) {
                    minioClient.putObject(
                        PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, file.length(), -1)
                            .contentType(file.getName().endsWith(".m3u8") ? "application/vnd.apple.mpegurl" : "video/MP2T")
                            .build()
                    );
                }
                if (file.getName().endsWith(".m3u8")) {
                    m3u8Url = endpoint + "/" + bucketName + "/" + objectName;
                }
            }
        }
        if (m3u8Url == null) {
            throw new RuntimeException("未找到m3u8文件");
        }
        return m3u8Url;
    }
}
